package com.y.architecture.login;

import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.y.architecture.R;
import com.y.architecture.base.BaseActivity;
import com.y.architecture.base_dialog.MyProgressDialog;
import com.y.architecture.base_net.ApiCallback;
import com.y.architecture.bean.User;
import com.y.architecture.util.NetWorkUtil;
import com.y.architecture.weather.Weather;
import com.y.architecture.weather.WeatherService;

import butterknife.BindView;


public class LoginActivity extends BaseActivity implements ILoginContact.ILoginView, View.OnClickListener {
    @BindView(R.id.login_edit_name)
    EditText etUserName;
    @BindView(R.id.login_edit_psw)
    EditText etPassword;

    @BindView(R.id.login_btn_commit)
    Button btn_commit;

    @BindView(R.id.login_textInputLayout_key)
    TextInputLayout textInputLayout_key;

    @BindView(R.id.login_check_remember)
    CheckBox checkBox_remember;

    @BindView(R.id.login_check_autoLogin)
    CheckBox checkBox_autoLogin;
    @BindView(R.id.login_edit_host)
    EditText mLoginEditHost;

    @BindView(R.id.login_edit_port)
    EditText mLoginEditPort;

    @BindView(R.id.login_tv_status)
    TextView mLoginTvStatus;

    private LoginHelper mLoginHelper;

    String name;
    String psw;
    String port;
    String host;

    MyProgressDialog dialog;

    @Override
    public int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void initViews(Bundle savedInstanceState) {

        mLoginHelper = new LoginHelper(this);
        //设置可以计数
        textInputLayout_key.setCounterEnabled(true);
        //计数的最大值
        textInputLayout_key.setCounterMaxLength(6);

        btn_commit.setOnClickListener(this);

        checkBox_remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (checkBox_remember.isChecked()) {
//                    Toast.makeText(LoginActivity.this, "记住密码", Toast.LENGTH_SHORT).show();
                    writeBoolean("ISCHECK", true);
                } else {
//                    Toast.makeText(LoginActivity.this, "不记住密码", Toast.LENGTH_SHORT).show();
                    writeBoolean("ISCHECK", false);
                }
            }
        });

        //显示是否记住密码
        rememberKey();

        checkBox_autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (checkBox_autoLogin.isChecked()) {
//                    Toast.makeText(LoginActivity.this, "自动登录", Toast.LENGTH_SHORT).show();
                    writeBoolean("AUTO_ISCHECK", true);

                    checkBox_remember.setChecked(true);
                    writeBoolean("ISCHECK", true);

                } else {
//                    Toast.makeText(LoginActivity.this, "不自动登录", Toast.LENGTH_SHORT).show();
                    writeBoolean("AUTO_ISCHECK", false);
                }
            }
        });
        //显示是否记住自动登录
//        autoLogin();
    }


    @Override
    public void showLoginSuccess() {
        btn_commit.setText("登录");
        mLoginTvStatus.setVisibility(View.GONE);
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void errorWarning(EditText view, String msg) {
        writeBoolean("AUTO_ISCHECK",false);
        mLoginTvStatus.setText(msg);
        mLoginTvStatus.setVisibility(View.VISIBLE);
        btn_commit.setClickable(true);
        if (view!=null){
            view.requestFocus();
        }
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void showLogging() {
        btn_commit.setClickable(false);
        btn_commit.setText("正在验证，请稍等。。");
    }

    @Override
    public void showNetWorkError() {
        Toast.makeText(this, "网络故障..", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void rememberKey() {
        name = readData("name");
        port = readData("port");
        host = readData("host");
        if (readBoolean("ISCHECK")) {
            checkBox_remember.setChecked(true);
            psw = readData("psw");
            etPassword.setText(psw);
        } else {
            checkBox_remember.setChecked(false);
            etPassword.setText("");
        }
        etUserName.setText(name);
        mLoginEditPort.setText(port);
        mLoginEditHost.setText(host);
    }

    @Override
    public void autoLogin() {
        if (readBoolean("AUTO_ISCHECK")) {
            checkBox_autoLogin.setChecked(true);
            rememberKey();
            attemptLogin();
        } else {
            checkBox_autoLogin.setChecked(false);
        }
    }

    @Override
    public void setStatus(boolean boo) {

    }

    @Override
    public String getInputText(EditText text) {
        return text.getText().toString();
    }

    private void attemptLogin() {
//        if (mAuthTask != null) {
//            return;
//        }
        // Check for a valid password, if the user entered one.
        if (mLoginHelper.validateInfo(mLoginEditHost)&&mLoginHelper.validateInfo(mLoginEditPort)
                &&mLoginHelper.validateInfo(etUserName)&&mLoginHelper.validateInfo(etPassword)){
            showToast("通过验证");
        }else{
            return;
        }


        // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
//            showProgress(true);
//            mAuthTask = new UserLoginTask(email, password);
//            mAuthTask.execute((Void) null);
            Log.e("attemptLogin: ","----" );
            name = etUserName.getText().toString();
            psw = etPassword.getText().toString();
            host = mLoginEditHost.getText().toString();
            port = mLoginEditPort.getText().toString();
            writeString("name", name);
            writeString("host", host);
            writeString("port", port);
            writeString("psw", psw);

            dialog = new MyProgressDialog();
            dialog.show(getSupportFragmentManager(),"1");
            try {
                showLogging();
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!NetWorkUtil.isNetWorkAvailable(this)) { //无网络，显示网络无连接
                showNetWorkError();
                return;
            }
//                mLoginHelper.attempLogin(etUserName.getText().toString(), etPassword.getText().toString(), Integer.parseInt(mLoginEditPort.getText().toString()),mLoginEditHost.getText().toString());
            WeatherService.getInstance().getData("厦门",
//                    password,Integer.parseInt(port),host,
                    new ApiCallback<Weather>() {
                @Override
                public void onError(Throwable e) {
                    errorWarning(null,e.getMessage());//显示登录失败
//                            getView().jumpActivity();
                    btn_commit.setText("登录");
                }

                @Override
                public void onNext(Weather user) {

                    showLoginSuccess(); //显示登录成功
                    //传递数据
                    Bundle bundle = new Bundle();
                    bundle.putString("name",etUserName.getText().toString());
//                        ArrayList<String> names = new ArrayList<String>();
//                        for (Store store: stores
//                             ) {
//                            names.add(store.getName());
//                        }
//                        bundle.putStringArrayList("storename",names);

//                    bundle.putParcelableArrayList("stores",stores);
////                        bundle.putSerializable("stores",stores);
//                    Log.e( "onSuccess: ", "门店"+stores);
//                    startActivity(MainActivity.class, bundle);
                    showToast("成功："+user.getHeWeather6().get(0).getNow().getCond_txt());
                }
            });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_btn_commit:
               attemptLogin();
                break;
        }
    }

    @Override
    public User getUser() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        LoginService.getInstance().onDestory();
    }
}
